﻿using Main.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Main.Engine
{
    partial class ServiceLocator : IServiceLocator
    {
        public static IServiceLocator Instance { get; private set; }
        static ServiceLocator() { Instance = new ServiceLocator(); }

        private Dictionary<Type, IService> SERVICES = new Dictionary<Type, IService>();
        private ServiceLocator()
        {
            LocateService();
            Replace<IWindowManager>(WindowManager.Instance);
            Replace<IComponentManager>(ComponentManager.Instance);
        }


        private void LocateService()
        {
            Type TypeOfService = typeof(IService);
            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (Type t in assembly.GetTypes().Where(o => TypeOfService.IsAssignableFrom(o)))
                {
                    if (t.IsClass && !t.IsAbstract)
                    {
                        ConstructorInfo cinfo = t.GetConstructor(Type.EmptyTypes);
                        if (cinfo != null && cinfo.IsPublic)
                        {
                            IService o = (IService)cinfo.Invoke(null);
                            foreach (Type iFace in t.GetInterfaces().Where(i => TypeOfService.IsAssignableFrom(i)))
                            {
                                if (SERVICES.ContainsKey(iFace))
                                    continue;
                                SERVICES.Add(iFace, o);
                            }
                        }
                    }
                }
            }
        }

    }
}
